package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exceptions.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.model.enums.LeaseStatus;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.attr.AttrValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.atguigu.lease.web.admin.vo.room.RoomDetailVo;
import com.atguigu.lease.web.admin.vo.room.RoomItemVo;
import com.atguigu.lease.web.admin.vo.room.RoomQueryVo;
import com.atguigu.lease.web.admin.vo.room.RoomSubmitVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【room_info(房间信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class RoomInfoServiceImpl extends ServiceImpl<RoomInfoMapper, RoomInfo>
        implements RoomInfoService {
    @Autowired
    private RoomAttrValueService roomAttrValueService;
    @Autowired
    private RoomFacilityService roomFacilityService;
    @Autowired
    private RoomLabelService roomLabelService;
    @Autowired
    private RoomPaymentTypeService roomPaymentTypeService;
    @Autowired
    private RoomLeaseTermService roomLeaseTermService;
    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private RoomInfoMapper roomInfoMapper;
    @Autowired
    private AttrValueMapper attrValueMapper;
    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private LabelInfoMapper labelInfoMapper;
    @Autowired
    private PaymentTypeMapper paymentTypeMapper;
    @Autowired
    private LeaseTermMapper leaseTermMapper;
    @Autowired
    private GraphInfoMapper graphInfoMapper;
    @Autowired
    private LeaseAgreementService leaseAgreementService;
    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;

    /**
     * 保存和更新房间信息
     * 先判断是保存还是更新，如果是更新-对于配置、标签、杂费等先删除中间表信息，再从新保存
     * @param roomSubmitVo
     */
    @Override
    public void customSaveOrUpdate(RoomSubmitVo roomSubmitVo) {
        //1.判断是保存还是更新
        boolean result = roomSubmitVo.getId() != null;
        //2.无论是保存还是更新都更新房间信息
        saveOrUpdate(roomSubmitVo);
        //3.通过回显获取id
        Long id = roomSubmitVo.getId();

        //更新房间信息
        if (result){
            //删除房间属性信息
            LambdaQueryWrapper<RoomAttrValue> roomAttrValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
            roomAttrValueLambdaQueryWrapper.eq(RoomAttrValue::getRoomId, id);
            roomAttrValueService.remove(roomAttrValueLambdaQueryWrapper);

            //删除配套信息
            LambdaQueryWrapper<RoomFacility> roomFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            roomFacilityLambdaQueryWrapper.eq(RoomFacility::getRoomId, id);
            roomFacilityService.remove(roomFacilityLambdaQueryWrapper);

            //删除标签信息
            LambdaQueryWrapper<RoomLabel> roomLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
            roomLabelLambdaQueryWrapper.eq(RoomLabel::getRoomId, id);
            roomLabelService.remove(roomLabelLambdaQueryWrapper);

            //删除支付方式
            LambdaQueryWrapper<RoomPaymentType> roomPaymentTypeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            roomPaymentTypeLambdaQueryWrapper.eq(RoomPaymentType::getRoomId, id);
            roomPaymentTypeService.remove(roomPaymentTypeLambdaQueryWrapper);

            //删除可选租期
            LambdaQueryWrapper<RoomLeaseTerm> roomLeaseTermLambdaQueryWrapper = new LambdaQueryWrapper<>();
            roomLeaseTermLambdaQueryWrapper.eq(RoomLeaseTerm::getRoomId, id);
            roomLeaseTermService.remove(roomLeaseTermLambdaQueryWrapper);

            //删除图片信息
            LambdaQueryWrapper<GraphInfo> graphLambdaQueryWrapper = new LambdaQueryWrapper<>();
            graphLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.ROOM);
            graphLambdaQueryWrapper.eq(GraphInfo::getItemId, id);
            graphInfoService.remove(graphLambdaQueryWrapper);
        }

        //保存属性信息
        List<Long> attrValueIds = roomSubmitVo.getAttrValueIds();
        if (!CollectionUtils.isEmpty(attrValueIds)){
            List<RoomAttrValue> roomAttrValues = new ArrayList<>(attrValueIds.size());
            for (Long attrValueId : attrValueIds){
                RoomAttrValue roomAttrValue = RoomAttrValue.builder().roomId(id).attrValueId(attrValueId).build();
                roomAttrValues.add(roomAttrValue);
            }
            roomAttrValueService.saveBatch(roomAttrValues);
        }

        //保存配套信息
        List<Long> facilityInfoIds = roomSubmitVo.getFacilityInfoIds();
        if (!CollectionUtils.isEmpty(facilityInfoIds)){
            List<RoomFacility> roomFacilities = new ArrayList<>(facilityInfoIds.size());
            for (Long facilityInfoId : facilityInfoIds){
                RoomFacility roomFacility = RoomFacility.builder().roomId(id).facilityId(facilityInfoId).build();
                roomFacilities.add(roomFacility);
            }
            roomFacilityService.saveBatch(roomFacilities);
        }

        //保存标签信息
        List<Long> labelInfoIds = roomSubmitVo.getLabelInfoIds();
        if (!CollectionUtils.isEmpty(labelInfoIds)){
            List<RoomLabel> roomLabels = new ArrayList<>(labelInfoIds.size());
            for (Long labelInfoId : labelInfoIds){
                RoomLabel roomLabel = RoomLabel.builder().roomId(id).labelId(labelInfoId).build();
                roomLabels.add(roomLabel);
            }
            roomLabelService.saveBatch(roomLabels);
        }

        //保存支付方式信息
        List<Long> paymentTypeIds = roomSubmitVo.getPaymentTypeIds();
        if (!CollectionUtils.isEmpty(paymentTypeIds)){
            List<RoomPaymentType> roomPaymentTypes = new ArrayList<>(paymentTypeIds.size());
            for (Long paymentTypeId : paymentTypeIds){
                RoomPaymentType paymentType = RoomPaymentType.builder().roomId(id).paymentTypeId(paymentTypeId).build();
                roomPaymentTypes.add(paymentType);
            }
            roomPaymentTypeService.saveBatch(roomPaymentTypes);
        }

        //保存可选租期信息
        List<Long> leaseTermIds = roomSubmitVo.getLeaseTermIds();
        if (!CollectionUtils.isEmpty(leaseTermIds)){
            List<RoomLeaseTerm> roomLeaseTerms = new ArrayList<>(leaseTermIds.size());
            for (Long leaseTermId : leaseTermIds){
                RoomLeaseTerm leaseTerm = RoomLeaseTerm.builder().roomId(id).leaseTermId(leaseTermId).build();
                roomLeaseTerms.add(leaseTerm);
            }
            roomLeaseTermService.saveBatch(roomLeaseTerms);
        }

        //保存图片信息
        List<GraphVo> graphVoList = roomSubmitVo.getGraphVoList();
        if (!CollectionUtils.isEmpty(graphVoList)){
            List<GraphInfo> graphInfoList = new ArrayList<>(graphVoList.size());
            for (GraphVo graphVo : graphVoList) {
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setUrl(graphVo.getUrl());
                graphInfo.setName(graphVo.getName());
                graphInfo.setItemId(id);
                graphInfo.setItemType(ItemType.ROOM);
                graphInfoList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfoList);
        }

    }

    /**
     * 根据条件进行分页查询房间列表信息
     * @param queryVo
     */
    @Override
    public void customPage(IPage<RoomItemVo> page, RoomQueryVo queryVo) {
        roomInfoMapper.customPage(page,queryVo);
    }

    /**
     * 根据id获取房间信息（修改回显）
     * @param id
     * @return
     */
    @Override
    public RoomDetailVo customGetById(Long id) {
        //创建一个结果对象，将查询到的房间信息插入到里面进行返回
        RoomDetailVo roomDetailVo = new RoomDetailVo();

        //查询房间基本信息
        RoomInfo roomInfo = getById(id);
        //通过BeanUtils可以直接将相同属性名的值进行赋值
        BeanUtils.copyProperties(roomInfo, roomDetailVo);

        //查询公寓信息
        ApartmentInfo apartmentInfo = apartmentInfoMapper.selectById(roomInfo.getApartmentId());
        roomDetailVo.setApartmentInfo(apartmentInfo);

        //查询房间属性
        List<AttrValueVo> attrValueVoList = attrValueMapper.roomQueryList(id);
        roomDetailVo.setAttrValueVoList(attrValueVoList);

        //查询房间配套信息
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.roomQueryList(id);
        roomDetailVo.setFacilityInfoList(facilityInfoList);

        //查询房间标签
        List<LabelInfo> labelInfoList = labelInfoMapper.roomQueryList(id);
        roomDetailVo.setLabelInfoList(labelInfoList);

        //查询支付方式
        List<PaymentType> paymentTypeList = paymentTypeMapper.roomQueryList(id);
        roomDetailVo.setPaymentTypeList(paymentTypeList);

        //查询可选租期
        List<LeaseTerm> leaseTerms = leaseTermMapper.roomQueryList(id);
        roomDetailVo.setLeaseTermList(leaseTerms);

        //图片信息
        List<GraphVo> graphVoList = graphInfoMapper.roomQueryList(ItemType.ROOM,id);
        roomDetailVo.setGraphVoList(graphVoList);

        return roomDetailVo;
    }

    /**
     * 根据id删除房间信息
     * @param id
     */
    @Override
    public void roomRemoveById(Long id) {
        //判断房间是否是在租状态，是的话不能删除
        LambdaQueryWrapper<LeaseAgreement> leaseAgreementLambdaQueryWrapper = new LambdaQueryWrapper<>();
        leaseAgreementLambdaQueryWrapper.in(LeaseAgreement::getStatus, LeaseStatus.SIGNED,LeaseStatus.WITHDRAWING,LeaseStatus.RENEWING);
        leaseAgreementLambdaQueryWrapper.eq(LeaseAgreement::getRoomId, id);
        long count = leaseAgreementService.count(leaseAgreementLambdaQueryWrapper);
        if (count > 0){
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }
        //可以删除房间
        //删除房间基本信息
        removeById(id);

        //删除房间对应的属性
        LambdaQueryWrapper<RoomAttrValue> roomAttrValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roomAttrValueLambdaQueryWrapper.eq(RoomAttrValue::getRoomId, id);
        roomAttrValueService.remove(roomAttrValueLambdaQueryWrapper);

        //删除房间对应的配套信息
        LambdaQueryWrapper<RoomFacility> roomFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roomFacilityLambdaQueryWrapper.eq(RoomFacility::getRoomId, id);
        roomFacilityService.remove(roomFacilityLambdaQueryWrapper);

        //删除房间对应的标签
        LambdaQueryWrapper<RoomLabel> roomLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roomLabelLambdaQueryWrapper.eq(RoomLabel::getRoomId, id);
        roomLabelService.remove(roomLabelLambdaQueryWrapper);

        //删除房间的支付方式信息
        LambdaQueryWrapper<RoomPaymentType> roomPaymentTypeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roomPaymentTypeLambdaQueryWrapper.eq(RoomPaymentType::getRoomId, id);
        roomPaymentTypeService.remove(roomPaymentTypeLambdaQueryWrapper);

        //删除房间可选租期信息
        LambdaQueryWrapper<RoomLeaseTerm> leaseTermLambdaQueryWrapper = new LambdaQueryWrapper<>();
        leaseTermLambdaQueryWrapper.eq(RoomLeaseTerm::getRoomId, id);
        roomLeaseTermService.remove(leaseTermLambdaQueryWrapper);

        //删除图片信息
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId, id);
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.ROOM);
        graphInfoService.remove(graphInfoLambdaQueryWrapper);

    }
}




